# coding:utf-8
import time
from django.shortcuts import render, redirect, HttpResponse
from web.forms.project import ProjectModelForm
from django.http import JsonResponse
from web import models
from utils.tencent_cos import create_bucket


def project_list(request):
    if request.method == 'GET':
        """
        从数据库中获取我参与和我创建的所有项目，包括星标项目和未星标项目
        """
        project_dic = {'star': [], 'my': [], 'join': []}
        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        for row in my_project_list:  # row为Project对象
            if row.star:
                project_dic['star'].append({'value': row, 'type': 'my'})
            else:
                project_dic['my'].append(row)
        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in join_project_list:
            if item.star:
                project_dic['star'].append({'value': item.project, 'type': 'join'})
            else:
                project_dic['join'].append(item.project)
        form = ProjectModelForm(request)
        return render(request, 'project_list.html', locals())
    form = ProjectModelForm(request, data=request.POST)
    if form.is_valid():
        name = form.cleaned_data['name']
        # 为项目创建桶
        bucket = '{}-{}-{}-1306108626'.format(name, request.tracer.user.phone, str(int(time.time())))
        region = 'ap-chengdu'
        create_bucket(bucket, region)
        # 通过验证的字段：项目名，颜色，描述信息，需要加creator才能创建表记录
        form.instance.bucket = bucket
        form.instance.region = region
        form.instance.creator = request.tracer.user
        form.save()
        return JsonResponse({'status': True, })
    return JsonResponse({'status': False, 'error': form.errors})


def project_star(request, project_type, project_id):
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect('project_list')
    elif project_type == 'join':
        models.ProjectUser.objects.filter(id=project_id, user=request.tracer.user).update(star=True)
        return redirect('project_list')
    else:
        return HttpResponse('请求错误')


def project_unstar(request, project_type, project_id):
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('project_list')
    elif project_type == 'join':
        models.ProjectUser.objects.filter(id=project_id, user=request.tracer.user).update(star=False)
        return redirect('project_list')
    else:
        return HttpResponse('请求错误')
